<template lang="pug">
div
  div(style='margin-bottom: 20px')
    Button(type='primary', @click="$router.push('pages/add')") 添加页面
  table.table
    thead
      tr
        td 标题
        td 更新日期
        td
    tbody
      tr(v-for='page in pages', :key='page.id')
        td {{ page.title }}
        td {{ page.changed }}
        td.text-center(width='150')
          Button(type='primary', size='small', @click='edit(page.id)') 编辑
          | &nbsp;&nbsp;
          Button(type='error', size='small', @click='remove(item)') 删除

  div.text-center(style='margin-top: 20px')
    Page(:current='page + 1', :total='total', :page-size='pageSize', size='small', show-total, @on-change='viewPage')
</template>

<script>
import Api from '@/apis/page'
import store from '@/store'

const pageSize = 10

function getPages (query) {
  let page = query.page || 0
  page = Math.max(page - 1, 0)

  const params = {
    gid: store.state.app.id,
    page,
    limit: pageSize
  }
  return Api.getPages(params).then(data => {
    return { data, params }
  })
}

export default {
  beforeRouteEnter (to, from, next) {
    getPages(to.query).then(({ data, params }) => {
      next(vm => {
        vm.page = params.page
        vm.total = data.total
        vm.pages = data.list
      })
    })
  },
  beforeRouteUpdate (to, from, next) {
    getPages(to.query).then(({ data, params }) => {
      this.page = params.page
      this.total = data.total
      this.pages = data.list
      next()
    })
  },
  data () {
    return {
      page: 0,
      total: 0,
      pageSize,
      pages: []
    }
  },
  methods: {
    edit (id) {
      this.$router.push(`/page/${id}/edit`)
    },
    viewPage (page) {
      this.$router.push({
        path: '',
        query: { page, gid: store.state.app.id }
      })
    }
  }
}
</script>
